<template>
  <div id="app">
    <router-view v-if="isRouterAlive"></router-view>
  </div>

</template>

<script>


import router, {resetRouter} from "@/router";

function addNewRoute(menuList) {
  console.log(menuList)
  let routes = router.options.routes
  console.log(routes)
  routes.forEach(routeItem=>{
    if(routeItem.path=="/Index"){
      menuList.forEach(menu=>{
        let childRoute =  {
          path:'/'+menu.menuclick,
          name:menu.menuname,
          meta:{
            title:menu.menuname
          },
          component:()=>import('./components/'+menu.menucomponent)
        }

        routeItem.children.push(childRoute)
      })
    }
  })

  resetRouter()
  router.addRoutes(routes)
}
export default {
  name: 'App',
  mounted() {
    window.addEventListener('unload', this.saveState)
  },

  data () {
    return {
      isRouterAlive: true
    }
  },
  provide(){ //提供
    return {
      reload: this.reload
    }
  },
  methods: {
    saveState() {
      localStorage.setItem('state', JSON.stringify(this.$store.state))
    },
    reload(){
      this.isRouterAlive = false
      this.$nextTick( function () {
        this.isRouterAlive = true
      })
    }
  },
  components: {

  },
  created () {
    // 在页面加载时读取localStorage
    if (localStorage.getItem('store')) {
      this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(localStorage.getItem('store'))))
      addNewRoute(this.$store.state.menu)
    }
    // 在页面刷新时将store保存到localStorage里
    window.addEventListener('beforeunload', () => {
      localStorage.setItem('store', JSON.stringify(this.$store.state))
    })
  }
}
</script>

<style>
#app {
  height: 100%;
}
</style>
